#!/usr/bin/env python
#-*- coding: utf-8 -*-
#__author__:vincentlc
#time: 16/5/28 : 20:54

'''
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
'''

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        n = 0
        result = []
        while 2**n <= len(root):
            tmp = root[2**n-1:2**(n+1)-1]
            result.append(list(filter(lambda x:x!='#',tmp)))
            n+=1

        return result

    def levelOrder2(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        parent_list = []
        result_val = []

        parent_list.append(root)

        child_list = []
        tmp_val= []

        while len(parent_list)!=0:
        # while parent_list:
            for parent in parent_list:
                tmp_val.append(parent.val)
                if parent.left != None:
                    child_list.append(parent.left)
                    # tmp_val.append(parent.left.val)

                if parent.right != None:
                    child_list.append(parent.right)
                    # tmp_val.append(parent.right.val)
            else:
                # parent_list = child_list.copy()
                parent_list = child_list
                result_val.append(tmp_val)
                child_list = []
                # child_list.clear()
                tmp_val = []
                # tmp_val.clear()

        return result_val


test_b = [3,9,20,'#','#',15,7]
cls_a = Solution()
print(cls_a.levelOrder(test_b))

t_a = TreeNode(3)
t_a.left = TreeNode(9)
t_a.right = TreeNode(20)
t_a.right.left = TreeNode(15)
t_a.right.right = TreeNode(7)

result_a = cls_a.levelOrder2(t_a)
print(result_a)
